<?php

namespace Account\Controller;

use Common\Controller\ApiController;
use Util\Curl;

class BankCardController extends ApiController {

    public function getList() {
        $card = D('BankCard')->where(['user_id' => $this->user['id']])->select();
        if (empty($card))
            $this->errorResponse(30013);
        $card = $this->bankIcon($card);
        $card = transform('BankCard', 'detail', $card);
        $this->response($card);
    }

    public function store() {
        $user = $this->user;
        $input = $this->request();
        $input['user_id'] = $user['id'];
        $bankCardModel = D('BankCard');
        $input['create_time'] = time();
        if ($bankCardModel->create($input)) {
            $id = $bankCardModel->add();
            $card = D('BankCard')->find($id);
            $card = transform('BankCard', 'detail', $card);
            $this->createdResponse($card);
        } else {
            $this->errorResponse(30015, $bankCardModel->getError());
        }
    }

    public function update() {
        $id = I('get.id');
        $input = $this->request();
        $card = D('BankCard')->find($id);
        if (empty($card))
            $this->errorResponse(30016);
        $bankCardModel = D('BankCard');
        if ($bankCardModel->create(array_merge($card, $input))) {
            $bankCardModel->save();
            $card = D('BankCard')->find($id);
            $card = transform('BankCard', 'detail', $card);
            $this->createdResponse($card);
        } else {
            $this->errorResponse(30015, $bankCardModel->getError());
        }

        // if (isset($input['bank'])) $card['bank'] = $input['bank'];
    }

    /*
     * 银行归属地查询，只能做一般查询
     */

    public function checkBank() {
        $input = $this->request();
        $number = str_replace(" ", '', $input['bankcard_num']);
        $banklist = \Util\BankInfo::banklist();
        $bankinfo = \Util\BankInfo::bankInfo($number, $banklist);
        if ($bankinfo) {
//            检验卡号是不是已经存在了
            $UserCard = D('BankCard');
            if($UserCard->getByAccount($number)){
                $this->errorResponse(400,'卡号已经存在了,不能重复绑定');
            }
            $this->createdResponse(['bankname' => $bankinfo, 'code' => 200]);
        }


        $this->errorResponse(400, '该卡号信息暂未录入');
    }

    /*
     * 银行归属地查询2,接入银联支付,没有接入成功，说是签名不对
     */

    public function checkBank_2() {
        $input = $this->request();
        $number = $input['bankcard_num'];
        $curl = new \Util\Curl();
        $unionpay = C('sdk.unionpay');
        if (empty(S('unionpay_token'))) {
            //获取token接口
            $url = "https://openapi.unionpay.com/upapi/cardbin{$unionpay['use_sandbox']}/token?app_id={$unionpay['app_id']}&app_secret={$unionpay['app_secret']}";
            $tokenstr = $curl->get($url);
            $tokenArr = json_decode($tokenstr, true);
            if (!empty($tokenArr['token'])) {
                S('unionpay_token', $tokenArr['token'], $tokenArr['expire_in']);
            }
        }
        //查询银行卡

        $cardno = json_encode(['cardNo' => $number]);
        $ts = $this->msectime();
        $ts = '1559069571419';
        $str = $unionpay['signature'] . '{"cardNo":"' . $number . '"}' . $ts; //签名
        $sign = hash('sha256', $str);
        $sign = "9a5b03957c1f4dde204475ec7a50f5df93014f51c8e8dcc4574a0b1e24bcd2a7";
        $token = S('unionpay_token'); //token
        $url_cardinfo = "https://openapi.unionpay.com/upapi/cardbin{$unionpay['use_sandbox']}/cardinfo?token={$token}&sign={$sign}&ts={$ts}";
        $data['cardNo'] = '6214830215395277';
        $header['content-type'] = 'applicationjson';
        $bankinfo = $curl->post($url_cardinfo, $data, $header);
        if ($bankinfo) {
            $this->createdResponse(['bankname' => $bankinfo, 'code' => 200]);
        }

        $this->errorResponse(400, '该卡号信息暂未录入');
    }

    /*
     * 银行卡四要素查询,接入聚合数据接口
     */

    public function verifybankcard4() {
        $input = $this->request();
        $id = $this->user['id'];
        $realname = $input['realname'];
        $idcard = $input['idcard'];
        $bank = $input['bank'];
        $bankcard = $input['bankcard'];
        $sub_branch = $input['sub_branch']? : '';
        $mobile = $input['mobile'];
        $juhe = C('sdk.juhe');
        //暂时不开启
//        $url = "http://v.juhe.cn/verifybankcard4/query.php?key={$juhe['key_verfiybank4']}&bankcard={$bankcard}&realname={$realname}&idcard={$idcard}&mobile={$mobile}";
//        $curl = new \Util\Curl();
//        $bankinfo = $curl->get($url);
        $bankinfo = json_decode($bankinfo, TRUE);
        if ($bankinfo['result']['res'] != 1) {
            //修改数据
            $UserCard = D('BankCard');
            try {
                $res3 = $UserCard->add([
                    'user_id' => $id,
                    'bank' => $bank,
                    'account' => $bankcard,
                    'cardholder' => $realname,
                    'mobile' => $mobile,
                    'sub_branch' => $sub_branch,
                    'create_time' => time(),
                    'create_ip' => get_client_ip()
                ]);
                if ($res3) {
                    $this->createdResponse();
                }
                $this->errorResponse('400', '填写信息用误，请从新填写');
            } catch (Exception $exc) {
                echo $exc->getTraceAsString();
                $this->errorResponse('400', '绑卡失败，请稍后再试');
            }
        }
        $this->errorResponse(400, $bankinfo['result']['message']);
    }

    /**
     * 绑定银行卡——可支持银行卡列表
     */
    public function getAllBank() {
        $banklist = \Util\BankInfo::banklist();
        $banklist = array_values($banklist);
        $this->response($banklist);
    }

    /*
     * 银行卡图标
     */
    private function bankIcon($bankcard) {
        $http = new Curl();
        if (is_array($bankcard)) {
            foreach ($bankcard as $k => $v) {
                if (empty($bankcard['icon'])) {
                    $bank_type_url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo={$v['account']}&cardBinCheck=true";
                    $bankinfo = $http->get($bank_type_url);
                    $bankinfo = json_decode($bankinfo, true);
                    if ($bankinfo) {
                        $bank_icon_url = "https://apimg.alipay.com/combo.png?d=cashier&t={$bankinfo['bank']}";
                        $bankcard[$k]['icon'] = $bank_icon_url;
                    }
                }
                D('BankCard')->save($bankcard[$k]);
            }
            
        } else {
            $bank_type_url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo={$bankcard}&cardBinCheck=true";
            $bankinfo = $http->get($bank_type_url);
            $bankinfo = json_decode($bankinfo, true);
            if ($bankinfo) {
                $bank_icon_url = "https://apimg.alipay.com/combo.png?d=cashier&t={$bankinfo['bank']}";
                $icon = $bank_icon_url;
                return $icon;
            }
        }

        return $bankcard;
    }

}
